package newcall.com.newcalldemo;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.m800.m800demo.R;
import com.m800.sdk.IM800Management;
import com.m800.sdk.M800Error;
import com.m800.sdk.M800SDK;
import com.m800.sdk.M800UserIdentity;
import com.m800.sdk.M800ValidationToken;
import com.m800.verification.M800CountryCode;
import com.m800.verification.M800PhoneVerifiedResult;
import com.m800.verification.M800VerificationClient;
import com.m800.verification.M800VerificationManager;
import com.m800.verification.M800VerificationManagerCallback;
import com.m800.verification.M800VerificationType;
import com.m800.verification.PhoneNumberInfo;

public class SignUpActivity extends AppCompatActivity  implements View.OnClickListener{

    private static final String DEBUG_TAG = "test";
    private TextView mCountryCodeTextView;
    private TextView tv_tip;
    private EditText mPhoneNumberEditText;
    private Button mNextButton;
    private IM800Management mM800Management;
    private M800VerificationManager mVerificationManager;

    private M800CountryCode mCountryCode;
    private String mInputPhoneNumber;
    private static final int REQ_SELECT_COUNTRY = 0;
    private static final int REQ_GET_VERIFICATION_CODE = 1;
    private static final int MSG_VERIFICATION_SUCCESS = 100;
    private static final int MSG_VERIFICATION_ERROR = 99;
    private static final int MSG_SIGN_UP_FAILED = 101;
    private static final int MSG_SIGN_UP_SUCCESS = 102;
    private static final int MSG_NEED_VERIFICATION = 103;
    private static final int ERROR_NEED_VERIFICATION = 20103;


    CheckBox checkbox;
    public boolean isMes;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);
        initView();
        init();
    }

    private void initView() {
        mCountryCodeTextView = (TextView) findViewById(R.id.et_country_code);
        tv_tip = (TextView) findViewById(R.id.tv_tip);
        mPhoneNumberEditText = (EditText) findViewById(R.id.et_phone_number);
        mNextButton = (Button) findViewById(R.id.btn_next);
        checkbox = (CheckBox) findViewById(R.id.checkbox);
        mCountryCodeTextView.setOnClickListener(this);
        mNextButton.setOnClickListener(this);
        checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    //
                    isMes=true;

                }
                else {
                    isMes=false;
                }
            }
        });
    }

    private void init() {
        mM800Management = M800SDK.getInstance().getManagement();
        mVerificationManager = M800VerificationClient.getVerificationManager(this);
        mVerificationManager.addCallback(mVerificationManagerCallback);

        // Get phone number info
        PhoneNumberInfo phoneNumberInfo = mVerificationManager.getPhoneNumberInfo();
        if (phoneNumberInfo != null) {
            mCountryCode = phoneNumberInfo.getDefaultCountryCode();
            mInputPhoneNumber = phoneNumberInfo.getDefaultPhoneNumber();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            //手机地区标号
            case REQ_SELECT_COUNTRY:
            if (resultCode == Activity.RESULT_OK) {
                String countryCodeJson = data.getStringExtra(SelectCountryActivity.EXTRA_SELECTED_COUNTRY);
                if (!TextUtils.isEmpty(countryCodeJson)) {
                    Gson gson = new Gson();
                    mCountryCode = gson.fromJson(countryCodeJson, M800CountryCode.class);
                    //刷新界面数据
                    updateCountryCodeText();

                }
            }
            break;
            case REQ_GET_VERIFICATION_CODE:
                // Add back verification manager callback
                mVerificationManager.addCallback(mVerificationManagerCallback);

                switch (resultCode) {
                    case Activity.RESULT_OK:
                        String requestId = data.getStringExtra(VerificationCodeActivity.EXTRA_REQUEST_ID);
                        mHandler.obtainMessage(MSG_VERIFICATION_SUCCESS, requestId).sendToTarget();
                        Log.e(DEBUG_TAG, "verification code success!"+requestId);
                        break;
                    case Activity.RESULT_CANCELED:
                        Log.e(DEBUG_TAG, "User cancelled verification code input!");
                        Toast.makeText(SignUpActivity.this,"取消",Toast.LENGTH_LONG).show();
                        mVerificationManager.abortPhoneVerification();
                    case VerificationCodeActivity.RESULT_ERROR:
                      Toast.makeText(SignUpActivity.this,"认证失败",Toast.LENGTH_LONG).show();
                        break;
                }
                break;


    }
    }
        public void updateCountryCodeText() {
            if (mCountryCode != null) {
                String text = mCountryCode.getName() + " +" + mCountryCode.getCallCode();
                mCountryCodeTextView.setText(text);
            } else {
                mCountryCodeTextView.setText("空");
            }
        }

    private M800VerificationManagerCallback mVerificationManagerCallback = new M800VerificationManagerCallback() {


        @Override
        public void onSuccess(M800VerificationType type, String requestId) {
            M800PhoneVerifiedResult m800PhoneVerifiedResult = mVerificationManager.getLastPhoneVerifiedResult();
            Log.d(DEBUG_TAG, "<Verification.onSuccess> requestId = " + m800PhoneVerifiedResult.getRequestId()
                    + " time:" + m800PhoneVerifiedResult.getVerifiedTime());
            mHandler.obtainMessage(MSG_VERIFICATION_SUCCESS, requestId).sendToTarget();


        }

        @Override
        public void onError(M800VerificationType type, int errorCode, String errorMessage) {
            Log.e(DEBUG_TAG, "<Verification.onError> Verification failed, error: " + errorMessage);
            Toast.makeText(SignUpActivity.this, "Verification failed, error:" + errorMessage,
                    Toast.LENGTH_SHORT).show();
            mHandler.obtainMessage(MSG_VERIFICATION_ERROR).sendToTarget();


        }

        @Override
        public void onWaitingToReceiveCode(int codeLength) {
            Log.d(DEBUG_TAG, "<Verification.onWaitingToReceiveCode> codeLength = " + codeLength);
            Intent intent = new Intent(SignUpActivity.this, VerificationCodeActivity.class);
            intent.putExtra(VerificationCodeActivity.EXTRA_CODE_LENGTH, codeLength);
            startActivityForResult(intent, REQ_GET_VERIFICATION_CODE);
            // Unregister the listener because this fragment won't be interested the callbacks anymore
            // VerificationCodeActivity will take care of it
            mVerificationManager.removeCallback(this);
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            //手机地区编号
            case R.id.et_country_code:
                startActivityForResult(new Intent(this, SelectCountryActivity.class), REQ_SELECT_COUNTRY);
            break;

            //验证
            case R.id.btn_next:
                if (isMes){
                    goNext();

                }
                else
                    {
                        signUp(null);
                }

            break;

        }
    }




    //直接短信验证
    private void goNext() {
//        // Hide soft input
//        View view = getActivity().getCurrentFocus();
//        if (view != null) {
//            InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
//            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
//        }

        if (isUserInputValid()) {
            mInputPhoneNumber = mPhoneNumberEditText.getText().toString().trim();

            startVerification();
        } else {
            Toast.makeText(this, "Invalid input!", Toast.LENGTH_SHORT).show();
        }
    }

    //判断非空
    private boolean isUserInputValid() {
        return mCountryCode != null && !TextUtils.isEmpty(mPhoneNumberEditText.getText().toString().trim());
    }



    //发送验证
    private void startVerification() {
        try {

                mVerificationManager.startSmsVerification(mCountryCode, mInputPhoneNumber);


        } catch (Exception e) {
            Toast.makeText(this, "Failed to start verification, error:" + e.getMessage(),
                    Toast.LENGTH_SHORT).show();
            return;
        }


    }


    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            int what = message.what;
            boolean enablePager = false;
            switch (what) {

                case MSG_VERIFICATION_SUCCESS:
                    tv_tip.setText("verification_success");
                    String requestId = (String) message.obj;
                    signUp(requestId);
                    break;
                case MSG_VERIFICATION_ERROR:
                    tv_tip.setText("verification_failed");
                    enablePager = true;
                    break;
                case MSG_SIGN_UP_FAILED:
                    tv_tip.setText("signup_failed");

                    enablePager = true;
                    break;
                case MSG_SIGN_UP_SUCCESS:
//                    new SignUpSuccessTask().execute(isRegisteredBefore);
//                    Intent intent = new Intent(getContext(), WelcomeActivity.class);
//                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//                    startActivity(intent);
                    tv_tip.setText("signup_success");
                    Toast.makeText(SignUpActivity.this,"登录成功",Toast.LENGTH_LONG).show();
                   //返回 重新调用  sdk
                    setResult(RESULT_OK,new Intent());
                    finish();
                    Log.d("test", "handleMessage: 成功返回");
                    break;
                case MSG_NEED_VERIFICATION:
                    // Start verification
//                    mSignUpViewContainer.setVisibility(View.GONE);
//                    // Update verification switch to notice the user he should verify the number
//                    mVerificationSwitch.setChecked(true);
//                   showChooseVerificationMethodDialog();
                    tv_tip.setText("MSG_NEED_VERIFICATION");

                    break;


        }
            return true;
    }});

    //登录
    private void signUp(@Nullable String requestId) {
//        updateViewForSignUp();
        Log.d("test", "signUp: requestId="+requestId+"\n"
                +"CountryCode="+mCountryCode.getCountryCode()+"\n"
                +"mInputPhoneNumber="+mInputPhoneNumber+"\n"
        );
        M800UserIdentity identity = new M800UserIdentity(mInputPhoneNumber,
                mCountryCode.getCountryCode(), M800UserIdentity.Type.PhoneNumber);
        boolean connect = M800SDK.getInstance().getManagement().connect();
        Log.d("test", "signUp: connect"+connect);
        mM800Management.signup(
                identity,
                requestId == null ? null : new M800ValidationToken(
                        requestId, null, M800ValidationToken.ValidationSource.M800VerificationSDK),
                IM800Management.M800Language.M800LanguageEnglish,
                new IM800Management.M800ManagementCallback() {
                    @Override
                    public void complete(boolean isSuccess, M800Error error, Bundle userInfo) {
                        Log.d(DEBUG_TAG, "M800SDK sign up complete, isSuccess = " + isSuccess);
                        if (isSuccess) {
                            mHandler.sendEmptyMessage(MSG_SIGN_UP_SUCCESS);
                        }
                        else {
                            //code 5 已登录或者已注册
                            Log.d("test", "Sign up error, code = " + error.getCode() + " msg = " + error.getMessage());
//                            if("5".equals(error.getCode()+"")){
//                                mHandler.sendEmptyMessage(MSG_SIGN_UP_SUCCESS);
//                                return;
//                            }
                            if (error.getCode() == ERROR_NEED_VERIFICATION)
                            {
                                mHandler.sendEmptyMessage(MSG_NEED_VERIFICATION);
                            } else {
                                mHandler.sendEmptyMessage(MSG_SIGN_UP_FAILED);
                            }
                        }
//                        logSignUpEvent(isSuccess, error);
                    }
                });
    }





}
